package com.lcz.ssm.controller;

import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by LuChunzhou on 2017/6/27.
 */
@Controller
@RequestMapping("/demo")
public class XMemcachedTestController {

    @Autowired
    private MemcachedClient memcachedClient;

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/xmemcached", method = RequestMethod.GET)
    public String xmemcached() {
        try {
            memcachedClient.set("string", 3600, "This is xmemcached:luchunzhou!");
            Map<InetSocketAddress, Map<String, String>> memcachedStats = memcachedClient.getStats();
            String helloWord = memcachedClient.get("string");
            StringBuilder strBuilder = new StringBuilder(helloWord);
            strBuilder.append("\n");
            for (Iterator<?> statsIterator = memcachedStats.entrySet().iterator(); statsIterator.hasNext();) {
                Map.Entry<InetSocketAddress, Map<String, String>> entry = (Map.Entry<InetSocketAddress, Map<String, String>>) statsIterator.next();

                strBuilder.append(entry.getKey() + ":" + entry.getValue());
                strBuilder.append("\n");
            }
            return strBuilder.toString();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (MemcachedException e) {
            e.printStackTrace();
        }
        return "";
    }
}
